package com.flux.action

import com.flux.dispatcher.Dispatcher
import io.reactivex.disposables.Disposable

/**
 * This class must be extended in order to give useful functionality to create RxAction.
 */
abstract class RxActionCreator(private val dispatcher: Dispatcher, private val manager: SubscriptionManager) {

    fun addRxAction(rxAction: RxAction, disposable: Disposable) {
        manager.add(rxAction, disposable)
    }

    fun hasRxAction(rxAction: RxAction): Boolean {
        return manager.contains(rxAction)
    }

    fun removeRxAction(rxAction: RxAction) {
        manager.remove(rxAction)
    }

    fun newAction(actionId: String, vararg data: Any): RxAction {
        if (actionId.isEmpty()) {
            throw IllegalArgumentException("Type must not be empty")
        }

        if (data.size % 2 != 0) {
            throw IllegalArgumentException("Data must be a valid list of key,value pairs")
        }

        return RxAction.type(actionId).build()
    }

    fun postRxAction(action: RxAction) {
        dispatcher.postRxAction(action)
    }
}